<template>
  <div class="upload-file-card">
    <el-dialog
      :title="cardTitle"
      :visible.sync="dialogVisible"
      :before-close="whenDialogClose"
      width="600px"
    >
      <el-form
        :inline="true"
        :model="formData"
        class="formData-box"
        :rules="formRules"
        ref="adviceForm"
      >
        <div class="search-form-corver">
          <el-form-item
            v-if="ifThird"
            label="第三方产品信息方:"
            prop="thirdInfoName">
            <el-input
              v-model="formData.thirdInfoName"
              placeholder="请输入" />
          </el-form-item>
        </div>
      </el-form>
      <div class="up-load-part">
        <div class="center">
          <div class="label">{{ upLoadLabel }}</div>
          <el-upload
            name="file"
            ref="upload"
            action="string"
            :show-file-list="false"
            :disabled="isLoading"
            :accept="uploadAccept"
            style="text-align: right;"
            :before-upload="handleBeforeUpload"
            :auto-upload="false"
            :on-change="fileChange"
            :http-request="handleUpload"
          >
            <div
              class="out-corver"
              v-if="!hasFile">
              <icon-font
                class="load-btn-corver"
                icon="iconicon-addpictures" />
              <slot name="upLoadDesc" />
            </div>
            <div
              class="sel-file"
              v-if="hasFile">
              <icon-font
                class="sel-file-icon"
                icon="iconfile" />
              <!-- <icon-font
                class="sel-file-icon"
                icon="iconcsv" /> -->
              <span>
                <a class="filename-limit">{{ fileName }}</a>
                <a>重新上传</a>
              </span>
            </div>
          </el-upload>
        </div>
      </div>
      <slot />
      <div class="btn-part">
        <el-button @click.stop="whenDialogClose">取消</el-button>
        <el-button
          type="primary"
          @click.stop="submitResult">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { setTimeout } from 'timers'
export default {
  name: 'UploadFileCard',
  data () {
    return {
      isLoading: false, // 上传按钮的禁用/是否开始上传
      isFileLoaded: false, // 是否完成上传
      upLoadBtnText: '选择上传文件',
      // 文件名称
      fileName: '',
      formData: {
        thirdInfoName: ''
      },
      formRules: {
        thirdInfoName: [
          { required: true, message: '第三方产品信息必填', trigger: 'change' }
        ]
      }
    }
  },
  props: {
    // 是否是上传第三方产品，第三方产品多了个表单
    ifThird: {
      type: Boolean,
      default: true
    },
    uploadAccept: {
      type: String,
      default: ''
    },
    upLoadLabel: {
      type: String,
      default: '上传文件'
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    cardTitle: {
      type: String,
      default: '批量导入'
    },
    // 上传接口地址
    uploadApi: {
      type: String,
      default: ''
    },
    // 与上传接口一同传递的参数
    params: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    // 是否已选择文件
    hasFile () {
      if (this.fileName) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    handleBeforeUpload (file, fileList) {
      let FileExt = file.name.replace(/.+\./, '') // 名字后缀
      const isLt10M = file.size / 1024 / 1024 < 10 // 文件大小
      const format = this.uploadAccept.includes(FileExt.toLowerCase())
      if (!format) {
        this.$message.error(`上传文件只支持${this.uploadAccept}类型!`)
      } else if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return isLt10M && format
    },
    handleUpload (data) {
      this.isLoading = true
      this.upLoadBtnText = data.file.name
      // 发起请求
      let fd = new FormData()
      fd.append('importFile', data.file)
      if (this.params) {
        for (let k in this.params) {
          fd.append(k, this.params[k])
        }
      }
      this.$axios({
        method: 'post',
        url: this.uploadApi,
        headers: { 'Content-Type': 'multipart/form-data' },
        data: fd
      })
        .then(res => {
          const { code, payload, msg } = res.data
          if (!Number(code)) {
            this.$message.success('上传成功')
            this.$emit('submitReady', res)
            this.whenDialogClose()
          } else {
            this.$message.error(msg)
          }
        })
        .catch(() => {
          // this.$message.error('文件上传失败，请重新选择')
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    fileChange (file, fileList) {
      // 通过这种代码来保证每次上传只有一个文件
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
      this.fileName = fileList[0].name
    },
    whenDialogClose () {
      this.formData.thirdInfoName = ''
      this.isLoading = false
      this.$refs.adviceForm.clearValidate()
      this.$refs.upload.clearFiles()
      this.fileName = ''
      this.$emit('closeUploadFile')
    },
    submitResult () {
      this.$refs.adviceForm.validate(valid => {
        // 验证通过，第三方批量导入时已填写第三方名称
        if (valid) {
          this.$emit('submitResult')
        }
      })
    }
  },
  mounted () {}
}
</script>
<style lang="less">
@import '../m-front-common/pc/assets/var.less';

.upload-file-card {
  .btn-part {
    display: flex;
    justify-content: flex-end;
    margin: 20px 0 0 0;
  }

  .up-load-part {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;

    .center {
      width: 55%;
      margin: 0 auto;
      display: flex;
      flex-direction: row;

      .label {
        width: 300px;
        flex: 1 0 1;
      }
    }
  }

  .load-success,
  .sel-file {
    width: 100px;
    margin: 0 auto;

    .sel-file-icon {
      font-size: 60px;
      color: #000;
      float: left;
    }

    span {
      white-space: nowrap;

      a {
        display: inline-block;
        vertical-align: top;
      }
    }

    .filename-limit {
      width: 120px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      text-align: left;
    }
  }

  .load-btn-corver {
    font-size: 60px;
    color: #2371c5;
  }

  .out-corver {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .upLoadDesc {
    font-size: @smallFontSize;
    color: @weakFontColor;
  }
}
</style>
